/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-01-21
 * Time: 16:39
 */
public class MySingleList {
    class Node {
        //定于成内部类
        public int val; //存储的数据
        public Node next;//存储下一个节点的地址

        public Node(int val) {
            this.val = val;  //不给next,如果没存的话，不知道下一个节点的地址
        }
    }

    public Node head; //代表当前链表的头结点的引用

    //遍历链表
    public void display() {
        Node cur = head;
        //遍历完之后,就不知道链表的head的头结点了 head==null了
        while (cur != null) {  //不能head.next!=null最后一个结点打印不到
            System.out.print(cur.val + " ");
            cur = cur.next; //head往后走
        }
        System.out.println();
    }


    //头插法
    public void addFirst(int data) {
        Node node = new Node(data);
        node.next = head;
        head = node;
        //思考,如果没有head呢 node的next赋为null，变成头节点，则不管有没有,均可以操作
    }

    //尾插法
    public void addLast(int data) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
            return;
        }
        Node cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
        //如果没有节点,head为空,cur.next发生空指针异常
    }

    public void createCycle() {
        Node cur = head;
        while(cur.next != null) {
            cur = cur.next;
        }
        cur.next = head.next.next;
    }

    public int detectCycle() {
        Node fast = head;
        Node slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                break;
            }
        }
        if(fast == null || fast.next == null) {
            return -1;
        }
        slow = head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast.val;
    }
}



